package org.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.atguigu.gmall.realtime.app.BaseApp;
import org.atguigu.gmall.realtime.bean.TrafficPageViewBean;
import org.atguigu.gmall.realtime.common.Constant;
import org.atguigu.gmall.realtime.util.AtguiguUtil;
import org.atguigu.gmall.realtime.util.FlinkSinkUtil;

import java.time.Duration;

/**
 * Project:gmallRealTime
 * Package:org.atguigu.gmall.realtime.app.dws
 * Author: ZengHaiFeng
 * CreateTime:2023/4/28 11:46:03
 * Description: Todo
 * Version：1.0
 */
public class Dws_02_DwsTrafficVcChArisNewPageViewWindow extends BaseApp {
    public static void main(String[] args) {
        new Dws_02_DwsTrafficVcChArisNewPageViewWindow()
                .init(40002,
                        2,
                        Constant.TOPIC_DWD_TRAFFIC_PAGE,
                        "Dws_02_DwsTrafficVcChArisNewPageViewWindow");
    }
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> ds) {
        // parse log to pojo
        SingleOutputStreamOperator<TrafficPageViewBean> parseStream = parseToPojo(ds);
        // window and aggregation
        SingleOutputStreamOperator<TrafficPageViewBean> resultSteam = windowAndAgg(parseStream);
        // output to clickhouse
        writeToClickHouse(resultSteam);
        //resultSteam.print();
    }

    private void writeToClickHouse(SingleOutputStreamOperator<TrafficPageViewBean> resultSteam) {
        resultSteam.addSink(FlinkSinkUtil.getClickHouseSink("dws_traffic_vc_ch_ar_is_new_page_view_window",
                TrafficPageViewBean.class));
    }

    private SingleOutputStreamOperator<TrafficPageViewBean> windowAndAgg(SingleOutputStreamOperator<TrafficPageViewBean> parseStream) {
            return parseStream
                    .assignTimestampsAndWatermarks(
                            WatermarkStrategy.
                                    <TrafficPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                    .withTimestampAssigner((bean,ts) -> bean.getTs())
                                    .withIdleness(Duration.ofSeconds(60)))
                    .keyBy(bean -> bean.getVc() + "_" + bean.getCh() + "_" + bean.getAr() + "_" + bean.getIsNew())
                    .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                    .reduce(new ReduceFunction<TrafficPageViewBean>() {
                        @Override
                        public TrafficPageViewBean reduce(TrafficPageViewBean value1, TrafficPageViewBean value2) throws Exception {
                            value1.setPvCt(value1.getPvCt() + value2.getPvCt());
                            value1.setDurSum(value1.getDurSum() + value2.getDurSum());
                            value1.setUvCt(value1.getUvCt() + value2.getUvCt());
                            value1.setSvCt(value1.getSvCt() + value2.getSvCt());
                            return value1;
                        }
                    }, new ProcessWindowFunction<TrafficPageViewBean, TrafficPageViewBean, String, TimeWindow>() {
                        @Override
                        public void process(
                                String s,
                                Context context,
                                Iterable<TrafficPageViewBean> elements,
                                Collector<TrafficPageViewBean> out) throws Exception {
                            TrafficPageViewBean bean = elements.iterator().next();
                            bean.setStt(AtguiguUtil.tsToDateTime(context.window().getStart()));
                            bean.setEdt(AtguiguUtil.tsToDateTime(context.window().getEnd()));
                            bean.setTs(System.currentTimeMillis());
                            out.collect(bean);
                        }
                    });
    }

    private SingleOutputStreamOperator<TrafficPageViewBean> parseToPojo(DataStreamSource<String> ds) {
        return ds
                .map(JSON::parseObject)
                .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
                .map(new RichMapFunction<JSONObject, TrafficPageViewBean>() {
                    private ValueState<String> lastVisitDateState;
                    @Override
                    public void open(Configuration parameters) {
                        lastVisitDateState = getRuntimeContext().getState(
                                new ValueStateDescriptor<>(
                                        "lastVisitDate",
                                        String.class));
                    }
                    @Override
                    public TrafficPageViewBean map(JSONObject value) throws Exception {
                        JSONObject common = value.getJSONObject("common");
                        String vc = common.getString("vc");
                        String ch = common.getString("ch");
                        String ar = common.getString("ar");
                        String isNew = common.getString("is_new");

                        JSONObject page = value.getJSONObject("page");
                        Long duringTime = page.getLong("during_time");
                        // get timestamp from value and convert to a date of string type
                        Long ts = value.getLong("ts");
                        String today = AtguiguUtil.tsToDate(ts);
                        String lastVisitDate = lastVisitDateState.value();

                        Long pvCt = 1L;
                        Long uvCt = 0L;
                        if (!today.equals(lastVisitDate)){
                            uvCt = 1L;
                            lastVisitDateState.update(today);
                        }
                        Long svCt = 0L;
                        String lastPageId = page.getString("last_page_id");
                        if (lastPageId == null || lastPageId.length() == 0){
                            svCt = 1L;
                        }
                        return new TrafficPageViewBean(
                                "", "", vc, ch, ar, isNew,
                                uvCt, svCt, pvCt,duringTime,ts);
                    }
                });
    }
}
